
package com.college.action.teacher;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.college.action.user.BaseAction;
import com.college.constant.AttachmentConstant;
import com.college.constant.JobOrderConstant;
import com.college.constant.SystemConstant;
import com.college.entity.Classes;
import com.college.entity.Course;
import com.college.entity.HomeWorkOrder;
import com.college.entity.JobLine;
import com.college.entity.JobLineSummaryInfo;
import com.college.entity.User;
import com.college.entity.UserClasses;
import com.college.entity.vo.AttachmentVo;
import com.college.entity.vo.ClassCourseVo;
import com.college.entity.vo.JobLineDetailVo;
import com.college.entity.vo.JsonVo;
import com.college.entity.vo.PageVo;
import com.college.exception.UploadException;
import com.college.service.JobOrderService;
import com.college.service.SystemUserService;
import com.college.service.TeacherService;
import com.college.util.ZipUtils;

/**
 * @author bob
 * 
 */

@Controller
@RequestMapping("user/teacher")
public class TeacherAction extends BaseAction {

	
	@Autowired
	private TeacherService teacherService;
	
	@Autowired
	private SystemUserService systemUserService;
	
	@Autowired
	private JobOrderService jobOrderService;

	

	/**
	 * 老师主页面
	 * @param request
	 * @param classEntity
	 * @return
	 */
	@RequestMapping(value = "index.htm", method = RequestMethod.GET)
	public String teacherIndex(HttpServletRequest request, @RequestParam(value = "p", defaultValue = "1") int currentPageNum,ModelMap modelMap) {
		// 查询老师发布的作业信息
		User user =  (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		PageVo<HomeWorkOrder> releasedHomeWorkPage = teacherService.getReleasedHomeWorkListPage(user.getUserId(),new HomeWorkOrder(),currentPageNum);
		
		List<Course> courseList = systemUserService.getCourseByClassIds(user.getClassIdList(),user.getUserId());
		
		modelMap.put("releasedHomeWorkPage", releasedHomeWorkPage);
		modelMap.put("courseList", courseList);
		return "teacher/pages/index";
	}
	
	
	
	@RequestMapping(value = "searchHomeWorkList.json", method = RequestMethod.POST)
	@ResponseBody
	public String searchHomeWorkList(HttpServletRequest request,HomeWorkOrder homeworkOrder, 
			@RequestParam(value = "p", defaultValue = "1") int currentPageNum,
			ModelMap modelMap) {
		// 查询老师发布的作业信息
		User user =  (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		PageVo<HomeWorkOrder> pageVo = teacherService.getReleasedHomeWorkListPage(user.getUserId(),homeworkOrder,currentPageNum);
		
		JSONObject json = new JSONObject();
		json.put("pageVo", pageVo);
		
		
		return json.toString();
	}
	
	
	
	/**
	 * 发布作业页面
	 * @param request
	 * @param classEntity
	 * @return
	 */
	@RequestMapping(value = "releaseHomeWork.htm", method = RequestMethod.GET)
	public String releaseHomeWorkPage(HttpServletRequest request, Classes classEntity) {
		//TODO 查询老师发布的作业信息
		return "teacher/pages/release";
	}
	
	
	

	/**
	 * 老师发布作业信息
	 * @param request
	 * @param classEntity
	 * @return
	 */
	@RequestMapping(value = "releaseHomeWork.json", method = RequestMethod.POST)
	@ResponseBody
	public JsonVo<String> releaseHomeWork(HttpServletRequest request,HomeWorkOrder homeWorkOrder) {
		//TODO 查询老师发布的作业信息
		JsonVo<String> json = new JsonVo<String>();
		String jobOrderId = UUID.randomUUID().toString();
		homeWorkOrder.setJobOrderId(jobOrderId);
		User user =  (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		homeWorkOrder.setTeacherId(user.getUserId());
		int num = teacherService.releaseHomeWork(homeWorkOrder);
		if(num > 0 && homeWorkOrder.getFile() != null){//上传作业附件
			String originalFileName = homeWorkOrder.getFile().getOriginalFilename();
			try {
				
				//初始化学生jobLine明细信息
				systemUserService.initJobLineDetailData(jobOrderId,homeWorkOrder.getClassId());
				systemUserService.addUploadFile(homeWorkOrder.getFile(), originalFileName, jobOrderId, AttachmentConstant.Kind.jobOrderFile,user.getUserId());
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		json.setResult(true);
		return json;
	}
	
	/**
	 * 老师更新作业的状态（trash：回收站,revert:还原）
	 * @param request
	 * @param classEntity
	 * @return
	 */
	@RequestMapping(value = "myReleasedHomeWorkStatus/update.json", method = RequestMethod.POST)
	@ResponseBody
	public JsonVo<String> myReleasedHomeWorkStatus(HttpServletRequest request,@RequestParam(value = "jobOrderId") String jobOrderId,
			@RequestParam(value = "orderStatus") JobOrderConstant.Status status) {
		JsonVo<String> json = new JsonVo<String>();
		//Article file = articleService.getArticleByArticleId(fileId);
		int num = jobOrderService.updateJobOrderStatusById(jobOrderId, new JobOrderConstant().convertToIntValue(status));
		if(num > 0){
			json.setResult(true);
		}else{
			json.setResult(false);
		}
		return json;
	}
	
	
	
	
	
	/**
	 * 老师对应的班级课程管理页面
	 * @param request
	 * @param classEntity
	 * @return
	 */
	@RequestMapping(value = "classCourseManage.htm", method = RequestMethod.GET)
	public String classCourseManagePage(HttpServletRequest request,ModelMap modelMap) {
		//老师加入到对应的班级
		User user =  (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		List<UserClasses> userClassesList = teacherService.getUserClassesCourseList(user.getUserId());
		modelMap.put("UserClassesList", userClassesList);
		return "teacher/pages/joinClasses";
	}
	
	
	
	@RequestMapping(value = "joinClasses.json", method = RequestMethod.POST)
	@ResponseBody
	public JsonVo<String> joinClasses(HttpServletRequest request, 
			@RequestParam(value = "classCode") String classCode,
			@RequestParam(value = "courseName") String courseName) {
		//老师加入到对应的班级
		User user =  (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		
		JsonVo<String> json = new JsonVo<String>();
		UserClasses existUserClasses  = systemUserService.getUserClassesByClassCode(classCode);
		Classes classes = systemUserService.getClassesByClassCode(classCode);
	
		try {
			if(existUserClasses != null){
				json.getErrors().put("classCode", "已加入此班级，无需重复加入");
			}else if(classes == null){
				json.getErrors().put("classCode", "班级邀请码错误");
			}
			// 检测校验结果
			validate(json);
			UserClasses userClasses = new UserClasses(user.getUserId(), classes.getClassId(),courseName,UUID.randomUUID().toString());
			int courseNum = teacherService.addCourse4Classes(userClasses);
			int result = teacherService.joinClasses(userClasses);
			
			
			List<String> list = new ArrayList<String>();
			list.add(classes.getClassId());
			user.setClassIdList(list);
			request.getSession().setAttribute(SystemConstant.SESSION_USER, user);
			json.setResult(result > 0 && courseNum > 0 ? true : false);
		} catch (Exception e) {
			json.setResult(false);
			json.setMsg(e.getMessage());
		}
		
		return json;
	}
	
	@RequestMapping(value = "getUserClassesCourseList.json", method = RequestMethod.GET)
	@ResponseBody
	public List<UserClasses> getUserClassesCourseList(HttpServletRequest request) {
		//老师加入到对应的班级
		User user =  (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		List<UserClasses> userClasses = teacherService.getUserClassesCourseList(user.getUserId());
		return userClasses;
	}
	

	@RequestMapping(value = "queryStuJobLinesDetail.htm", method = RequestMethod.GET)
	public String queryStuJobLinesDetail(HttpServletRequest request,
			@RequestParam("jobOrderId") String jobOrderId,
			@RequestParam("homeWorkName") String homeWorkName,
			@RequestParam("className") String className,
			@RequestParam("courseName") String courseName,
			ModelMap modelMap) throws UnsupportedEncodingException {
	
		List<JobLineDetailVo> jobLineList = teacherService.queryStuJobLinesDetail(jobOrderId);
		
		List<AttachmentVo> jobLineAttachmentList = teacherService.getJobLineAttachmentList(jobOrderId);
		
		for(JobLineDetailVo jobLineDetail:jobLineList){
			for(AttachmentVo attachmentVo:jobLineAttachmentList){
				if(jobLineDetail.getJobLineId().equals( attachmentVo.getForeignKeyId())){
					jobLineDetail.setAttachmentVo(attachmentVo); 
					break;
				}
			}
		}
		
		modelMap.put("stuHomeWorkDetailList", jobLineList);
		
		
		JobLineSummaryInfo jobLineSummaryInfo = teacherService.queryJobLinesSummaryInfo(jobOrderId);
		
		HomeWorkOrder summaryJobOrder = new HomeWorkOrder();
		summaryJobOrder.setHomeWorkName(new String(homeWorkName.getBytes("ISO-8859-1"), "UTF-8"));
		summaryJobOrder.setCourseName(new String(courseName.getBytes("ISO-8859-1"), "UTF-8"));
		summaryJobOrder.setClassName(new String(className.getBytes("ISO-8859-1"), "UTF-8"));
		summaryJobOrder.setJobOrderId(new String(jobOrderId.getBytes("ISO-8859-1"), "UTF-8"));
		modelMap.put("summaryJobOrder",summaryJobOrder);
		modelMap.put("jobLineSummaryInfo",jobLineSummaryInfo);
		
		return "teacher/pages/stuHomeWorkDetail";
	}
	
	
	@RequestMapping(value = "joinClassPage.htm", method = RequestMethod.GET)
	public String joinClassPage(HttpServletRequest request,ModelMap modelMap) {
		return "student/pages/joinClasses";
	}
	
	@RequestMapping(value = "updateStuJobLine.json", method = RequestMethod.POST)
	@ResponseBody
	public JsonVo<String> updateStuJobLine(HttpServletRequest request,
			@RequestParam("jobLineId")String jobLineId,
			@RequestParam("score") double score,
			@RequestParam("comment") String comment,
			ModelMap modelMap) throws UnsupportedEncodingException {
		JsonVo<String> json = new JsonVo<String>();
		JobLine jobLine = new JobLine(jobLineId,score,comment);
	    int num = teacherService.updateStuJobLine(jobLine);
	
	    json.setResult(num > 0  ? true : false);
	    
		return json;
	}
	
	@RequestMapping(value = "download.json", method = { RequestMethod.GET })
	public void downloadStuAttachments(HttpServletRequest request,HttpServletResponse response,
			@RequestParam("jobOrderId") String jobOrderId,
			ModelMap modelMap) throws IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		List<AttachmentVo> jobLineAttachmentList = teacherService.getJobLineAttachmentList(jobOrderId);
		
		ClassCourseVo classCourseVo = teacherService.getClassCourseInfoByJobOrdeId(jobOrderId);
		
		long fileLength = 0 ;
		String targetPath = null;
		String zipName = classCourseVo.getClassName()+"-"+classCourseVo.getCourseName()+"-"+classCourseVo.getHomeWorkName()+".zip";
		if(jobLineAttachmentList != null && !jobLineAttachmentList.isEmpty()){
			String[] paths = new String[jobLineAttachmentList.size()];
			String[] newPaths = new String[jobLineAttachmentList.size()];
			String templatePath = jobLineAttachmentList.get(0).getPath();
			String prefixPath = templatePath.substring(0,templatePath.lastIndexOf("/"));//"/upload/2015/10/04"
			String suffixPath = templatePath.substring(templatePath.lastIndexOf("."),templatePath.length());
			for(int i = 0, l =jobLineAttachmentList.size() ; i < l ; i++ ){
				paths[i] = SystemConstant.COLLEGE_CCOS_ROOT + jobLineAttachmentList.get(i).getPath();
				newPaths[i] = SystemConstant.COLLEGE_CCOS_ROOT + prefixPath +"/" + jobLineAttachmentList.get(i).getStuNumber() 
						+ "_" + jobLineAttachmentList.get(i).getRealName()+suffixPath;
			}
			targetPath = SystemConstant.COLLEGE_CCOS_ROOT + zipName;//班级_课程_作业
			ZipUtils.writeZip(paths, newPaths,targetPath);
			fileLength = new File(targetPath).length();
			
		}else{
			ZipUtils.writeZip(new String[0],new String[0], targetPath);
		}
		
		//String downLoadPath = SystemConstant.COLLEGE_CCOS_ROOT + filePath;// order_文件名.后缀

		//response.setContentType(contentType);
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(zipName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));
		
		bis = new BufferedInputStream(new FileInputStream(targetPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();

	}
	
	
}
